//
//  UITextField+Mango.m
//  Mango
//
//  Created by 胡超 on 2020/12/10.
//  Copyright © 2020年 胡超., ltd. All rights reserved.
//

#import <objc/runtime.h>

#import "UITextField+Mango.h"

@implementation UITextField (Mango)

- (void)setLeftViewWidth:(CGFloat)width {
    self.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, self.frame.size.height)];
    self.leftViewMode = UITextFieldViewModeAlways;
}

- (void)setRightViewWidth:(CGFloat)width {
    self.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, self.frame.size.height)];
    self.rightViewMode = UITextFieldViewModeAlways;
}

- (NSRange)selectedRange {
    UITextPosition* beginning = self.beginningOfDocument;
    
    UITextRange* selectedRange = self.selectedTextRange;
    UITextPosition* selectionStart = selectedRange.start;
    UITextPosition* selectionEnd = selectedRange.end;
    
    const NSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart];
    const NSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd];
    
    return NSMakeRange(location, length);
}

- (void)setSelectedRange:(NSRange)range {
    UITextPosition* beginning = self.beginningOfDocument;
    
    UITextPosition* startPosition = [self positionFromPosition:beginning offset:range.location];
    UITextPosition* endPosition = [self positionFromPosition:beginning offset:range.location + range.length];
    UITextRange* selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition];
    
    [self setSelectedTextRange:selectionRange];
}

#pragma mark - MAX Input

- (NSString *)mg_lastText {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setMg_lastText:(NSString *)mg_lastText {
    objc_setAssociatedObject(self, @selector(mg_lastText), mg_lastText, OBJC_ASSOCIATION_COPY);
}

- (NSInteger)maxInputLength {
    return [objc_getAssociatedObject(self, _cmd) integerValue];
}

- (void)setMaxInputLength:(NSInteger)maxInputLength {
    objc_setAssociatedObject(self, @selector(maxInputLength), @(maxInputLength), OBJC_ASSOCIATION_COPY);
    [self addTarget:self action:@selector(mg_onTextFieldEditingChanged) forControlEvents:UIControlEventEditingChanged];
}

- (void)mg_onTextFieldEditingChanged {
    NSString *lang = [self textInputMode].primaryLanguage;
    if ([lang isEqualToString:@"zh-Hans"]) {
        //输入简体中文内容
        //获取高亮部分，如拼音
        UITextRange *selectedRange = [self markedTextRange];
        UITextPosition *position = [self positionFromPosition:selectedRange.start offset:0];
        if (!position) {
            [self handleTextFieldMaxInput];
        }
    } else {
        //输入简体中文以外的内容
        [self handleTextFieldMaxInput];
    }
}

- (void)handleTextFieldMaxInput {
    if (self.text.length > self.maxInputLength) {
        self.text = self.mg_lastText;
        return;
    }
    self.mg_lastText = self.text;
}

@end
